const mongoose = require('mongoose')
const glob = require('glob')
const { join } = require('path')


const base = 'mongodb://localhost/node_advance02'

mongoose.Promise = global.Promise

module.exports.initSchemas = () => {
  glob.sync(join(__dirname, './schema', '**/*.js')).forEach(require)
}

module.exports.initAdmin = async () => {
  const User = mongoose.model('User')
  let user = await User.findOne({
    username: 'gemini'
  })

  if (!user) {
    const user = new User({
      username: 'gemini',
      email: 'onebyonly@outlook.com',
      password: 'dark2333',
      role: 'admin'
    })
    await user.save()
  }
}
module.exports.connect = () => {
  let maxConnectTimes = 0

  return new Promise( (resolve, reject) => {
    if (process.env.NODE_ENV !== 'production') mongoose.set('debug', true)


    mongoose.connect(base, { useNewUrlParser: true})
    const db = mongoose.connection

    db.on('disconnected', () => {

      maxConnectTimes++

      if (maxConnectTimes > 5) throw new Error('数据库挂了')

      mongoose.connect(base)
    })

    db.on('error', err => {

      maxConnectTimes++

      if (maxConnectTimes > 5) throw new Error('数据库挂了')

      mongoose.connect(base)
    })

    db.once('open', () => {
      // 测试数据
      // const Dog = mongoose.model('Dog', { name: String })
      // const doga = new Dog({name: '叮叮当当'})

      // doga.save().then((err, doc) => {
      //   console.log('ok')
      // })
      resolve()
      console.log('Mongoose Connected successfully!')
    })
  })
}